package com.dingding.web.activity;

import javax.annotation.Resource;

import org.apache.log4j.Logger;

import com.dingding.common.core.base.dto.FacadeResult;
import com.dingding.common.core.util.ToolUtil;
import com.dingding.common.core.util.paravalidate.ValidateUtil;
import com.dingding.common.core.util.tools.wechat.WechatTool;
import com.dingding.facde.activity.dto.commonactivity.ReqGetActivityIndex;
import com.dingding.facde.activity.dto.commonactivity.ReqGetInviteInfo;
import com.dingding.facde.activity.dto.commonactivity.ReqRegFromActivity;
import com.dingding.facde.activity.dto.commonactivity.ReqStartAnActivity;
import com.dingding.facde.activity.dto.commonactivity.ReqStartToRegIndex;
import com.dingding.facde.activity.dto.commonactivity.ResGetActivityIndex;
import com.dingding.facde.activity.dto.commonactivity.ResGetInviteInfo;
import com.dingding.facde.activity.dto.commonactivity.ResRegFromActivity;
import com.dingding.facde.activity.dto.commonactivity.ResStartAnActivity;
import com.dingding.facde.activity.dto.commonactivity.ResStartToRegIndex;
import com.dingding.facde.activity.service.IActivityFacade;
import com.dingding.facde.activity.service.ICommonActivityFacade;
import com.dingding.facde.share.IShareActivityFacade;
import com.dingding.web.base.action.BaseAction;

/**
 * @Description:通用的活动的Action
 * @author fengshuonan
 * @date 2016年9月20日 下午3:32:27
 * @version 叮叮搭车
 * @since 2.4
 */
@SuppressWarnings("all")
public class ComActAction extends BaseAction {

	// 活动相关接口
	@Resource(name = "commonActivityFacade")
	private ICommonActivityFacade commonActivityFacade;

	@Resource(name = "shareActivityFacade")
	private IShareActivityFacade shareActivityFacade;

	@Resource(name = "activityFacade")
	private IActivityFacade activityFacade;

	Logger log = Logger.getLogger(this.getClass());

	/**
	 * @Description:检查是否已经发起过分享链接
	 * @author fengshuonan
	 * @since 2.4
	 */
	public String checkIsShare() {

		System.out.println(request.getRequestURL().toString());

		String userId = super.getPara("userId");
		String activityId = super.getPara("activityId");
		if (ToolUtil.validateParas(userId, activityId)) {
			super.writeNullParaError();
			return NONE;
		}

		FacadeResult<Boolean> startedAnActivity = this.commonActivityFacade.isStartedAnActivity(userId, activityId);
		super.writeFacade(startedAnActivity);

		return NONE;
	}

	/**
	 * @Description:获取发起分享首页的信息
	 * @author fengshuonan
	 * @since 2.4
	 */
	public String getShareIndexInfo() {

		System.out.println(request.getRequestURL().toString());

		String userId = super.getPara("userId");
		String activityId = super.getPara("activityId");
		ReqGetActivityIndex reqGetActivityIndex = new ReqGetActivityIndex(userId, activityId);

		boolean flag = ValidateUtil.validateBean(reqGetActivityIndex, ReqGetActivityIndex.class);
		if (flag != true) {
			super.writeNullParaError();
			return NONE;
		}

		FacadeResult<ResGetActivityIndex> activityIndexInfo = this.commonActivityFacade
				.getActivityIndexInfo(reqGetActivityIndex);
		super.writeFacade(activityIndexInfo);

		return NONE;
	}

	/**
	 * @Description:获取当前邀请详情
	 * @author fengshuonan
	 * @since 2.4
	 */
	public String getInviteInfo() {

		String userId = super.getPara("userId");
		String activityId = super.getPara("activityId");
		ReqGetInviteInfo reqGetInviteInfo = new ReqGetInviteInfo(userId, activityId);

		boolean flag = ValidateUtil.validateBean(reqGetInviteInfo, ReqGetInviteInfo.class);
		if (flag != true) {
			super.writeNullParaError();
			return NONE;
		}

		FacadeResult<ResGetInviteInfo> facade = this.commonActivityFacade.getInviteInfo(reqGetInviteInfo);
		super.writeFacade(facade);

		return NONE;
	}

	/**
	 * @Description:发起分享（点击分享时请求）
	 * @author fengshuonan
	 * @since 2.4
	 */
	public String publishShare() {

		String userId = super.getPara("userId");
		String giftId = super.getPara("giftId");
		String activityId = super.getPara("activityId");
		ReqStartAnActivity reqStartAnActivity = new ReqStartAnActivity(userId, giftId, activityId);

		boolean flag = ValidateUtil.validateBean(reqStartAnActivity, ReqStartAnActivity.class);
		if (flag != true) {
			super.writeNullParaError();
			return NONE;
		}

		FacadeResult<ResStartAnActivity> facade = this.commonActivityFacade.startAnActivity(reqStartAnActivity);
		super.writeFacade(facade);

		return NONE;
	}

	/**
	 * @Description:获取手机验证码
	 * @author fengshuonan
	 * @since 2.4
	 */
	public String getValidateCode() {

		String telephone = super.getPara("telephone");

		if (ToolUtil.isBlank(telephone)) {
			super.writeNullParaError();
			return NONE;
		}

		boolean flag = this.shareActivityFacade.sendPhoneMsg(telephone);

		if (flag) {
			super.writeResponseJsonp(200, "发送成功");
		} else {
			super.writeResponseJsonp(500, "服务器异常");
		}

		return NONE;
	}

	/**
	 * @Description:跳转到注册页面前的action
	 * @author fengshuonan
	 * @since 2.4
	 */
	public String startLogin() {

		String code = super.getPara("code"); // 为网页授权API回调时返回，用于获取用户的openId
		String activityId = super.getPara("activityId");
		String shareKey = super.getPara("shareKey");

		if (ToolUtil.isBlank(code)) {
			return ERROR;
		}

		// 通过返回的code去获取用户的openId
		String openId = WechatTool.getOpenIDByCode(code);

		// 判断该openId是否存在于库中
		FacadeResult<ResStartToRegIndex> result = this.commonActivityFacade
				.startToRegIndex(new ReqStartToRegIndex(openId, activityId));
		if (result.getCode() != 200) {
			return ERROR;
		}

		ResStartToRegIndex resStartToRegIndex = result.getObject();
		resStartToRegIndex.setShareKey(shareKey);
		request.setAttribute("result", resStartToRegIndex);
		int userType = resStartToRegIndex.getUserType(); // 1：新用户 （没有openid记录）
															// 2：老用户（有openId记录）
															// 3：老用户（有openId记录，并且发起过活动）
		// 如果是信用户，跳转到注册页面
		if (userType == 1) {
			return super.redirect("/dingding-web/laxin/judgeFromServer/register.html" + "?openId=" + openId
					+ "&activityId=" + activityId + "&shareKey=" + shareKey);

			// 如果是老用户并且没发起过活动，跳转到您已注册页面
		} else if (userType == 2) {
			return super.redirect("/dingding-web/laxin/judgeFromServer/olduser.html");

			// 如果是老用户发起过活动的，跳转到邀请详情页面
		} else {

			// 如果邀请人数够了，跳转到邀请够的页面
			if (resStartToRegIndex.getInviteNum() >= resStartToRegIndex.getEnoughNum()) {
				return super.redirect("/dingding-web/laxin/judgeFromServer/successinvite.html" + "?activityId="
						+ activityId + "&userId=" + resStartToRegIndex.getUserId());
			} else {
				return super.redirect("/dingding-web/laxin/judgeFromServer/successinvite.html" + "?activityId="
						+ activityId + "&userId=" + resStartToRegIndex.getUserId());
			}
		}
	}

	/**
	 * @Description:微信注册
	 * @author fengshuonan
	 * @since 2.4
	 */
	public String regFromWechat() {

		String telephone = super.getPara("telephone");
		String phoneCode = super.getPara("phoneCode");
		String graphCode = super.getPara("graphCode");
		String shareKey = super.getPara("shareKey");

		// 验证请求参数是否为空
		ReqRegFromActivity reqRegFromActivity = new ReqRegFromActivity(telephone, phoneCode, graphCode, shareKey);
		boolean valiFlag = ValidateUtil.validateBean(reqRegFromActivity, ReqRegFromActivity.class);
		if (valiFlag == false) {
			super.writeNullParaError();
			return NONE;
		}

		// 验证图形验证码是否正确
		String sessionGraphCode = super.getSessionGraphCode();
		if (!sessionGraphCode.equals(graphCode.trim().toLowerCase())) {
			super.writeResponseJsonp(400, "图形验证码错误");
			return NONE;
		}

		FacadeResult<ResRegFromActivity> facade = this.commonActivityFacade.regFromActivity(reqRegFromActivity);
		super.writeFacade(facade);
		return NONE;
	}

	/**
	 * @Description:获取电话手机号验证码
	 * @author fengshuonan
	 * @return String
	 * @since 2.4
	 */
	public String getTelePhoneCode() {

		String telephone = super.getPara("telephone");

		if (ToolUtil.isBlank(telephone)) {
			super.writeResponseJsonp(400, "手机号码为空");
			return NONE;
		}

		FacadeResult<Boolean> facade = this.commonActivityFacade.sendPhoneMsg(telephone);
		super.writeFacade(facade);
		return NONE;
	}

	/**
	 * @Description:注册用户（优惠券活动的）
	 * @author fengshuonan
	 * @since 2.4
	 */
	public String regUserCouponActi() {

		String telephone = super.getPara("telephone");
		String phoneCode = super.getPara("phoneCode");
		String graphCode = super.getPara("graphCode");
		String shareKey = super.getPara("shareKey");
		String activityId = super.getPara("activityId");

		// 验证请求参数是否为空
		ReqRegFromActivity reqRegFromActivity = new ReqRegFromActivity(null, telephone, phoneCode, graphCode, shareKey,
				activityId);
		boolean valiFlag = ValidateUtil.validateBean(reqRegFromActivity, ReqRegFromActivity.class);
		if (valiFlag == false) {
			super.writeNullParaError();
			return NONE;
		}

		// 验证图形验证码是否正确
		String sessionGraphCode = super.getSessionGraphCode();
		if (!sessionGraphCode.equals(graphCode.trim().toLowerCase())) {
			super.writeResponseJsonp(400, "图形验证码错误");
			return NONE;
		}

		// 判断是否活动已经结束，活动结束就不走注册业务(结束包括日期期限到了，还有优惠券领取完)
		// 判断活动是否结束返回的状态(1:优惠券领取完毕 4：活动到期 0：活动还在进行 5:异常)
		FacadeResult<ResRegFromActivity> result = FacadeResult.SUCCESS(new ResRegFromActivity());
		int judgeActivityFinish = judgeActivityFinish(activityId);
		if (judgeActivityFinish == 1) {
			result.getObject().setUserType(1);// 状态1是，提示优惠券发放完
			super.writeFacade(result);
			return NONE;
		} else if (judgeActivityFinish == 4) {
			result.getObject().setUserType(4);// 状态4是，提示活动结束
			super.writeFacade(result);
			return NONE;
		} else if (judgeActivityFinish == 5) {
			result.getObject().setUserType(5);// 状态5是，提示服务器异常
			super.writeFacade(result);
			return NONE;
		}

		FacadeResult<ResRegFromActivity> facade = this.commonActivityFacade.regFromCoupon(reqRegFromActivity);

		// facade返回的可能的情况（手机验证码为空，shareKey错误，添加用户异常）
		if (facade.getCode() != 200) {
			super.writeFacade(facade);
			return NONE;
		} else {
			
			//判断userId是否为空
			if(facade.getObject() == null || facade.getObject().getUserId() == null){
				result.getObject().setUserType(5);// 领取失败
				super.writeFacade(facade);
				return NONE;
			}

			// 调用接口，判断是否领取过(3:已经领取过优惠券 2：没有领取过优惠券 5：异常)
			int judgeUserIsGotCoupon = this.judgeUserIsGotCoupon(activityId, facade.getObject().getUserId());
			
			if (judgeUserIsGotCoupon == 3) {
				result.getObject().setUserType(3);// 已经领取过优惠券
				super.writeFacade(result);
				return NONE;
			} else if (judgeUserIsGotCoupon == 2) {
				
				// 调用接口，领取优惠券，增加用户一个优惠券
				int joinActivity = this.joinActivity(facade.getObject().getUserId());
				if (joinActivity == 2) {
					result.getObject().setUserType(2);// 没有领取过优惠券,领取成功
					super.writeFacade(result);
					return NONE;
				
				// 领取失败
				} else {
					result.getObject().setUserType(5);// 领取失败
					super.writeFacade(result);
					return NONE;
				}

			} else {
				result.getObject().setUserType(5);// dubbo 判断用户是否领取异常
				super.writeFacade(result);
				return NONE;
			}
		}
	}

	/**
	 * @Description 扫二维码送券的入口(6元优惠券)
	 * @author fengshuonan
	 */
	public String scanCoupon() {
		String activityId = getPara("activityId");
		String shareKey = getPara("shareKey");

		if (ToolUtil.isBlank(activityId) || ToolUtil.isBlank(shareKey)) {
			return this.redirectError();
		}

		// 判断活动是否结束(1:优惠券领取完毕 4：活动到期      0：活动还在进行 5:异常)
		int judgeActivityFinish = judgeActivityFinish(activityId);
		if (judgeActivityFinish == 1) {
			return this.redirectEmptyCoupon();
		} else if (judgeActivityFinish == 4) {
			return this.redirectActiFinish();
		} else if (judgeActivityFinish == 5) {
			return redirectError();
		} else {
			// 活动没有结束跳转至 登录领券-首页
			return super.forward(
					"/laxin/judgeFromServer/register.html" + "?&activityId=" + activityId + "&shareKey=" + shareKey);
		}
	}
	
	/**
	 * @Description 跳转到优惠券已经领完界面
	 * @author fengshuonan
	 */
	private String redirectEmptyCoupon() {
		return redirectByCode(1, 0);
	}

	/**
	 * @Description 跳转到得到优惠券页面
	 * @author fengshuonan
	 */
	private String redirectGetCoupon() {
		return redirectByCode(2, 0);
	}

	/**
	 * @Description 跳转到已经获得优惠券，不能重复领
	 * @author fengshuonan
	 */
	private String redirectRepeatGetCoupon() {
		return redirectByCode(3, 0);
	}

	/**
	 * @Description 跳转到活动已结束
	 * @author fengshuonan
	 */
	private String redirectActiFinish() {
		return redirectByCode(4, 0);
	}

	private String redirectByCode(int status, int code) {
		return super.redirect("/dingding-web/laxin/successRegister.html?status=" + status + "&code=" + code);
	}

	/**
	 * @Description 跳转到异常页面
	 * @author fengshuonan
	 */
	private String redirectError() {
		return super.redirect("/dingding-web/laxin/error.html");
	}
}
